<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class Order extends Model
{
    use HasDateTimeFormatter;

    protected $fillable = ['order_number', 'user_id', 'mobile', 'school_id', 'type', 'unit_block_id', 'room_number', 'amount', 'handling_fee', 'order_taking_fee', 'cut_off_at', 'pickup_code', 'write_off_code', 'write_off_code_url', 'description', 'images', 'status', 'paid_at'];
    protected $casts = [
        'images' => 'array',
    ];
    protected $appends = ['place', 'images_src'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function school()
    {
        return $this->belongsTo(School::class);
    }

    public function unitBlock()
    {
        return $this->belongsTo(UnitBlock::class);
    }

    public function runErrand()
    {
        return $this->belongsTo(RunErrand::class);
    }


    public function place(): Attribute
    {
        if ($this->unit_block_id) {
            $place = $this->unitBlock->name . ' ' . $this->room_number;
        } else {
            $place = $this->room_number;
        }
        return Attribute::make(get: fn() => $place);
    }

    public function imagesSrc(): Attribute
    {
        $images = collect($this->images)->map(function ($image) {
            return Storage::disk('oss')->url($image);
        })->toArray();
        return Attribute::make(get: fn() => $images);
    }


    public function writeOffCodeUrlOss(): Attribute
    {
        return Attribute::make(get: fn() => $this->write_off_code_url ? Storage::disk('oss')->url($this->write_off_code_url) : null);
    }
}
